package edu.nf.project.utils;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author CSY
 * @date 2025 - 06 - 11
 * 加密工具 - SHA-256
 */
public class SHA256Util {
    /**
     * 使用SHA-256加密方式对密码进行加密
     * @param pwd
     * @return
     */
    public static String encrypt(String pwd) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest(pwd.getBytes(StandardCharsets.UTF_8));
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < hash.length; i++) {
                String hex = Integer.toHexString(0xff & hash[i]);
                if (hex.length() == 1) hexString.append('0');
                hexString.append(hex);
            }
            String a = hexString.toString();
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 对密码进行验证
     * @param pwd 密码
     * @param encryptPwd 加密后的密码
     * @return
     */
    public static Boolean verify(String pwd,String encryptPwd) {
        String encrypt = encrypt(pwd);
        return encrypt.equals(encryptPwd);
    }
}
